package com.qf.group.common.base.handler;

import cn.hutool.core.util.ReflectUtil;
import com.qf.group.common.base.dto.ArgsErrorInfo;
import com.qf.group.common.base.result.ResponseResult;
import com.qf.group.common.base.result.ResultStatus;
import com.qf.group.common.base.ex.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author 13782
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseResult<Object> handlerException(Exception ex) {
        ex.printStackTrace();
        log.error("错误的信息:{}", ex.getMessage());
        return ResponseResult.error();
    }


    @ExceptionHandler(BaseException.class)
    public ResponseResult<Object> handlerException(BaseException ex) {
        ex.printStackTrace();
        return ResponseResult.error(ex.getResultStatus());
    }


    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseResult<List<ArgsErrorInfo>> handlerException(ConstraintViolationException ex) {
        ex.printStackTrace();
        return ResponseResult.error(ResultStatus.ARGS_VALID_ERROR, ex.getConstraintViolations().stream().map(violation -> {
            List<Path.Node> nodeList = (List<Path.Node>) ReflectUtil.getFieldValue(violation.getPropertyPath(), "nodeList");
            return ArgsErrorInfo.builder().filedName(nodeList.get(nodeList.size() - 1).getName()).errorMessage(violation.getMessage()).build();
        }).collect(Collectors.toList()));
    }

    @ExceptionHandler(BindException.class)
    public ResponseResult<List<ArgsErrorInfo>> handlerException(BindException ex) {
        ex.printStackTrace();
        return ResponseResult.error(ResultStatus.ARGS_VALID_ERROR, ex.getBindingResult().getFieldErrors().stream().map(fieldError -> ArgsErrorInfo.builder().filedName(fieldError.getField()).errorMessage(fieldError.getDefaultMessage()).build()).collect(Collectors.toList()));
    }

}
